<?php

/**
 * @filename PaperAboutAction.class.php 
 * @encoding UTF-8 
 * @author nemo.xiaolan <a href="mailto:335454250@qq.com">335454250@qq.com</a>
 * @link <a href="http://www.sep-v.com">http://www.sep-v.com</a>
 * @license http://www.sep-v.com/code-license
 * @datetime 2013-11-13  13:19:26
 * @Description
 * 
 */
class PaperAboutAction extends CommonAction {
    /**
     * Stockin
     */
    protected $modelName;
    
    /**
     * StockinDetail
     */
    protected $modelDetailName;
    
    /**
     * stockin_id
     * order_id
     * stockout_id
     */
    protected $mainRowIdField;
    
    /**
     * 'field', 'field'=>"input.type"
     */
    protected $ajaxRowFields;
    
    protected $checkStoreNumModels = array(
        "Orders", "StockTransfer"
    );
    
    protected $hasPriceModels = array(
        "Orders", "Purchase"
    );
    
    /**
     * workflow
     */
    protected $workflowAlias;
    
    public function _initialize() {
        parent::_initialize();
    }
    
    public function index() {
        parent::index($this->modelName."View");
    }
    
    
    /**
     * 编辑入库单/出库单/订单明细
     */
    public function editDetail() {
        $id = abs(intval($_GET["id"]));
        if(!$id) {
            //@todo
            return;
        }
        
        $this->assignPaperDetail($id);
        $this->display();
    }
    
    /**
     * 保存单据明细并提交
     */
    public function saveDetail() {
        $id = abs(intval($_POST["id"]));
//        echo $_POST["node_id"];exit;
        $model = D($this->modelName);
        if($id and $_POST["willsave"]) {
            $model->updateStatus($id,1);
        }
        if($_POST["total_price_hide"]) {
            $model->where("id=".$id)->save(array("total_price_real" => $_POST["total_price_hide"]));
        }
        /**
         * 自动执行保存订单
         */
        $workflow = new Workflow($this->workflowAlias);
        $node_id = $_POST["node_id"] ? abs(intval($_POST["node_id"])) : "";
        $node = $workflow->doNext($id, $node_id, true);
        $this->redirect("/JXC/".MODULE_NAME);
    }
    
    /**
     * 单据详情
     */
    public function viewDetail() {
        $this->assignPaperDetail($_GET["id"]);
        try {
            $this->display();
        } catch (ThinkException $e) {
            $this->display("paperViewDetail");
        }
        
    }
//    
//    /**
//     * 库管确认单据 提交出/入库
//     * 1、更改状态
//     * 2、改变库存清单
//     */
//    public function confirmDetail() {
//        $id = abs(intval($_GET["id"]));
//        if(!$id) {
//            $this->error(L("params_error"));
//        }
//        
//        $map = array(
//            "stockin_id" => $id
//        );
//        $stockinDetailView = D("StockinDetailView");
//        $data = $stockinDetailView->where($map)->select();
//        
//        $stockin = D("Stockin");
//        $stockid = $stockin->where("id=".$id)->getField("stock_id");
//        
//        $stockProductListModel = D("StockProductList");
//        $stockProductListModel->startTrans();
//        $rs = $stockProductListModel->updateStoreList($data, $stockid);
//        
//        if($rs) {
//            $stockProductListModel->commit();
//            $stockinModel = D("Stockin");
//            $stockinModel->updateStatus($id, 2);
//            $this->redirect("/JXC/Stockin");
//        } else {
//            $stockProductListModel->rollback();
//            $this->error(L("operate_failed"));
//        }
//        
//    }
    
    public function assignPaperDetail($id) {
        $id = abs(intval($id));
        if(!$id) {
            $this->errorPage(404);
            return;
        }
        
        
        $viewModel = D($this->modelName."View");
        $thePaper = $viewModel->find($id);
//        echo $viewModel->getLastSql();exit;
        if(!$thePaper) {
            $this->errorPage(404);
            return;
        }
        
        $detailViewModel = D($this->modelDetailName."View");
        $map = array(
            $this->modelDetailName.".".$this->mainRowIdField => $id
        );
        $this->_base_filter($map);
        $detailList = $detailViewModel->where($map)->order("id ASC")->group("id")->select();
//        echo $detailViewModel->getLastSql();exit;
        $workflow = new Workflow($this->workflowAlias);
        $process = $workflow->getItemProcesses($this->modelName, $id, $this->relationModel);
        
        import("@.TableView.TableView");
        $table = new TableView(MODULE_NAME."ViewDetail");
        $table->onlyList = true;
        $this->assign("TableView", $table->makeHorizontalTable($detailList));
        
        $this->assign("workflowProcesses", $process);
        $this->assign("list", $detailList);
        $this->assign("thePaper", $thePaper);
    }
    
    /**
     * @ajax
     * 增加订单明细一条数据
     * @todo 从stock_product_list表中取数据，根据factory_code_all，若不存在说明库存不足，存在则判断库存
     */
    public function ajax_addProduct() {
        
        $factory_code_all = $_GET["factory_code_all"];
        $attrs = extraFactoryCodeAll($factory_code_all);
        
        $mainrow_id = abs(intval($_GET["mainRowIdField"]));
        $sourcePaperModel = D($this->modelName);
        $sourcePaper = $sourcePaperModel->find($mainrow_id);
        $fromStockField = $this->fromStockField ? $this->fromStockField : "stock_id";
        
        $goods = D("GoodsView");
        $theGoods = $goods->where("factory_code_all='".$factory_code_all."'")->find();
//        print_r($theGoods);
//        echo $goods->getLastSql();
//        print_r($this->ajaxRowFields);exit;
        if(!$theGoods) {
            $this->ajaxReturn(array("message" => L("operate_failed")));
            return;
        }
        if(in_array($this->modelName, $this->checkStoreNumModels) and !checkStoreNum($factory_code_all, 1, $sourcePaper[$fromStockField])) {
            $this->ajaxReturn(array("message" => L("store_num_not_full")));
            return;
        }
        
        $goods_id = $theGoods["id"];
        
        $detail = D($this->modelDetailName);
        $data = array(
            $this->mainRowIdField => $mainrow_id,
            "color_id" => $attrs["color_id"],
            "standard_id" => $attrs["standard_id"],
            "goods_id" => $goods_id,
        );
        
        $rs = $detail->where($data)->select();
//        echo $detail->getLastSql();
        if($rs) {
            return;
        }
        
        if(in_array($this->modelName, $this->hasPriceModels)) {
            $data["per_price"] = $theGoods["price"];
            $data["price"] = $theGoods["price"];
        }
        $data["num"] = 1;
        $data["factory_code_all"] = sprintf($factory_code_all);
        $lastId = $detail->add($data);
        if(!$lastId) {
            $this->ajaxReturn(array(
                "message" => L("add_failed"),
            ));
        } else {
            $detailView = D($this->modelDetailName."View");
            $data = $detailView->find($lastId);
            /**
             * 如果存在金额字段，计算总金额
             */
            if(isset($data["price"])) {
                $this->updateTotalAmount($detail, $data[$this->mainRowIdField]);
            }
            if($this->ajaxRowFields) {
                $html = '<tr rowid="'.$data["id"].'">';
                foreach($this->ajaxRowFields as $k => $v) {
                    if(!$v) {
                        $html.= sprintf('<td>%s</td>', $data[$k]);
                    } else {
                        list($_type, $_extra) = explode(".", $v);
                        switch($_type) {
                            case "input":
                                $html .= sprintf('<td><input rowid="%s" type="text" class="input_%s" style="width:50px;" value="%s" %s /></td>',$lastId,$k, $data[$k], $_extra);
                                break;
                            case "span":
                                $html.= sprintf('<td><span class="%s">%s</span></td>', $_extra, $data[$k]);
                                break;
                        }
                    }
                }
                $html.= sprintf('<td><a href="javascript:paper.del_product(\'%s\',this);" class="btn btn-mini btn-info"><i class="icon icon-trash"></i> %s</a>', $data["id"], L("delete"));
                $html .= "</td></tr>";
            }   
            $this->ajaxReturn(array(
                "message" => "",
                "html" => $html
            ));
        }
    }
    
    /**
     * @todo 判断库存是否够
     */
    public function ajax_updateProductNum() {
        $id = abs(intval($_GET["id"]));
        $num = intval($_GET["num"]);
        
        $detail = D($this->modelDetailName);
        
        $data["num"] = $num;
        $detailView = D($this->modelDetailName."View");
        $theDetail = $detailView->find($id);
        
        if(in_array($this->modelName, $this->checkStoreNumModels) and !checkStoreNum($theDetail["factory_code_all"], $num)) {
            $this->ajaxReturn(array("message" => L("store_num_not_full")));
            return;
        }
        
        if(isset($theDetail["price"])) {
            $data = array(
                "price" => $num * $theDetail["per_price"],
                "num" => $num
            );
            $detail->where("id=".$id)->save($data);
        } else {
            $detail->where("id=".$id)->save(array("num" => $num));
        }
        $this->updateTotalAmount($detail, $theDetail[$this->mainRowIdField]);
    }
    
    public function ajax_delProduct() {
        $id = abs(intval($_GET["id"]));
        if(!$id) {
            $this->ajaxReturn(array(
                "message" => L("please_select_product")
            ));
        }
        
        $detail = D($this->modelDetailName);
        $theDetail = $detail->find($id);
        $rs = $detail->where("id=".$id)->delete();
        if(!$rs) {
            $this->ajaxReturn(array(
                "message" => L("delete_failed")
            ));
        }
        
        $this->updateTotalAmount($detail, $theDetail[$this->mainRowIdField]);
    }
    
    public function ajax_updatePrice() {
        $id = abs(intval($_GET["id"]));
        $price = $_GET["price"];
        
        $detail = D($this->modelDetailName);
        $detail->where("id=".$id)->save(array(
            "price" => $price
        ));
        $theDetail = $detail->find($id);
        $this->updateTotalAmount($detail, $theDetail[$this->mainRowIdField]);
    }
    
    public function ajax_updatePerPrice() {
        $id = abs(intval($_GET["id"]));
        $num = abs(intval($_GET["num"]));
        $price = $_GET["price"];
        $detail = D($this->modelDetailName);
        $detail->where("id=".$id)->save(array(
            "per_price" => $price,
            "price"     => $price*$num
        ));
    }
    
    /**
     * 更新总数量/总金额
     */
    private function updateTotalAmount($detail, $mainRowId) {
        $map = array(
            $this->mainRowIdField => $mainRowId
        );
        $paper = D($this->modelName);
        $total_price = $detail->where($map)->sum('price');
        $total_num = $detail->where($map)->sum('num');
        $paper->where("id=".$mainRowId)->save(array(
            "total_num" => $total_num,
            "total_price" => $total_price,
            "total_price_real" => $total_price
        ));
    }
    
}

?>
